package com.mixsmart.web.plugins;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mixsmart.commonweb.IWebConstant;
import com.mixsmart.commonweb.plugins.IPlugin;
import com.mixsmart.core.bean.MixResponse;
import com.mixsmart.core.service.IResQueryService;
import com.mixsmart.utils.StringUtils;
import com.mixsmart.web.plugins.bean.AutoComplete;

/**
 * 自动完成插件实现类
 * @author lmq
 * @version 1.0
 * @since 1.0
 * 2015年11月6日
 */
@Component("autoComplete")
public class AutoCompletePlugin implements IPlugin {

	@Autowired
	private IResQueryService resQueryServ;
	
	@SuppressWarnings("unchecked")
	@Override
	public <E> MixResponse<E> getDatas(String resName, HashMap<String, Object> params) {
		MixResponse<E> mixResp = new MixResponse<E>();
		try {
			List<AutoComplete> autoCompleteList = null;
			if(StringUtils.isNotEmpty(resName)) {
				MixResponse<Object> resp = resQueryServ.getDatas(resName, params);
				if(IWebConstant.OP_SUCCESS.equals(resp.getResult())) {
					List<Object> objs = resp.getDatas();
					resp = null;
					autoCompleteList = new ArrayList<AutoComplete>();
					AutoComplete autoComplete = null;
					for (Object obj : objs) {
						Object[] objArray = (Object[]) obj;
						autoComplete = new AutoComplete();
						if(objArray.length>=3) {
							autoComplete.setId(StringUtils.handNull(objArray[0]));
							autoComplete.setValue(StringUtils.handNull(objArray[1]));
							autoComplete.setLabel(StringUtils.handNull(objArray[2]));
						} else if(objArray.length==2) {
							autoComplete.setId(StringUtils.handNull(objArray[0]));
							autoComplete.setValue(StringUtils.handNull(objArray[1]));
							autoComplete.setLabel(StringUtils.handNull(objArray[1]));
						} else if(objArray.length==1) {
							autoComplete.setId(StringUtils.handNull(objArray[0]));
							autoComplete.setValue(StringUtils.handNull(objArray[0]));
							autoComplete.setLabel(StringUtils.handNull(objArray[0]));
						}
						autoCompleteList.add(autoComplete);
					}
					autoComplete = null;
					objs = null;
					mixResp.setResult(IWebConstant.OP_SUCCESS);
					mixResp.setMsg(IWebConstant.OP_SUCCESS_MSG);
					mixResp.setDatas((List<E>)autoCompleteList);
					autoCompleteList = null;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mixResp;
	}

	@Override
	public <E> MixResponse<E> getDatasPage(String resName, HashMap<String, Object> params, int page, int rows) {
		// TODO Auto-generated method stub
		return null;
	}

	
	
}
